package com.china08.yxyapi.api.manage.tec.teaching.lecture.pack;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.LimitOperation;
import org.springframework.data.mongodb.core.aggregation.SkipOperation;
import org.springframework.data.mongodb.core.aggregation.SortOperation;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePack;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePack.Res;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.util.DateToolUtils;

import io.swagger.annotations.ApiOperation;

/**
 * 老师 ---备授课--授课列表查询
 * 
 */
@CrossOrigin
@RestController
public class LectureSchPackController extends YxyApiBaseController {

    @Autowired
    private MongoTemplate mt;

    @ApiOperation(value = "老师授课列表查询")
    @RequestMapping(value = "/api_yw/manage/tec/teaching/lecture/pack/sch", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel)
            throws ParseException {
        String bookContent = reqModel.bookContent;
        String classId = reqModel.classId;
        String beginDate = reqModel.beginDate;
        String endDate = reqModel.endDate;
        String keyword = reqModel.keyword;
        String userId = getProfile(request, response).getId();
        String schoolId = getProfile(request, response).getSchoolId();
        Assert.notNull(StringUtils.defaultIfBlank(userId, null), "用户id必须");
        Assert.notNull(StringUtils.defaultIfBlank(schoolId, null), "学校id必须");
        Pageable pageable = reqModel.getPageable(Direction.DESC, "preDate");
        Criteria criteria = Criteria.where("userId").is(userId).and("schoolId").is(schoolId);
        if (StringUtils.isNotBlank(bookContent)) {
            criteria = criteria.and("bookcontentsId").is(bookContent);
        }
        if (StringUtils.isNotBlank(classId)) {
            criteria = criteria.and("classId").is(classId);
        }
        if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
            // 转化为UTC格式
            beginDate = beginDate.replace("Z", " UTC");
            endDate = endDate.replace("Z", " UTC");

            Date bdate = format.parse(beginDate);
            Date edate = format.parse(endDate);

            beginDate = DateToolUtils.format(bdate, DateToolUtils.FORMAT_SHORT_YMD);
            endDate = DateToolUtils.format(edate, DateToolUtils.FORMAT_SHORT_YMD);

            LocalDate lBDate = LocalDate.parse(beginDate);
            LocalDate lEDate = LocalDate.parse(endDate);
            criteria = criteria.and("preDate").gte(lBDate).lte(lEDate);
        } else if (StringUtils.isNotBlank(beginDate)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
            // 转化为UTC格式
            beginDate = beginDate.replace("Z", " UTC");
            Date bdate = format.parse(beginDate);
            beginDate = DateToolUtils.format(bdate, DateToolUtils.FORMAT_SHORT_YMD);
            LocalDate lBDate = LocalDate.parse(beginDate);
            criteria = criteria.and("preDate").gte(lBDate);
        } else if (StringUtils.isNotBlank(endDate)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
            // 转化为UTC格式
            endDate = endDate.replace("Z", " UTC");

            Date edate = format.parse(endDate);

            endDate = DateToolUtils.format(edate, DateToolUtils.FORMAT_SHORT_YMD);

            LocalDate lEDate = LocalDate.parse(endDate);
            criteria = criteria.and("preDate").lte(lEDate);
        } else {
            // 如果没有选择时间 默认全部(>=2000-01-01) ASC排序
            LocalDate currDate = LocalDate.ofYearDay(2000, 01);
            criteria = criteria.and("preDate").gte(currDate);
        }
        if (StringUtils.isNotBlank(keyword)) {
            Pattern pattern = Pattern.compile("^.*" + keyword + ".*$", Pattern.CASE_INSENSITIVE);
            criteria = criteria.and("packName").regex(pattern);
        }
        SkipOperation operation = new SkipOperation((pageable.getPageNumber() + 1 - 1) * pageable.getPageSize());
        LimitOperation limitOperation = new LimitOperation(pageable.getPageSize());
        SortOperation sortOperation = new SortOperation(pageable.getSort());
        TypedAggregation<YxyLecturePack> aggregation = Aggregation.newAggregation(YxyLecturePack.class, sortOperation,
                Aggregation.match(criteria), operation, limitOperation);
        Query query = new Query();
        query.addCriteria(criteria);
        long total = mt.count(query, YxyLecturePack.class);
        AggregationResults<YxyLecturePack> aggregationResults = mt.aggregate(aggregation, YxyLecturePack.class);
        List<RespModel> listModel = new ArrayList<LectureSchPackController.RespModel>();
        for (YxyLecturePack yxyLecturePack : aggregationResults) {
            RespModel model = new RespModel();
            List<ResModel> resModels = new ArrayList<LectureSchPackController.ResModel>();
            for (Res respModel : yxyLecturePack.getResources()) {
                ResModel resModel = new ResModel();
                resModel.formatId = respModel.getFormatId();
                resModel.title = respModel.getResourceName();
                resModel.orderNum = respModel.getOrderNum() != null ? respModel.getOrderNum() : 0;
                resModel.courseType = respModel.getCourseType();
                Integer fileSize = respModel.getFileSize();
                if (null != fileSize) {
                    resModel.fileSize = fileSize;
                } else {
                    resModel.fileSize = 0;
                }
                resModels.add(resModel);
            }
            resModels = resModels.stream().sorted((p1, p2) -> p1.orderNum.compareTo(p2.orderNum))
                    .collect(Collectors.toList());
            model.id = yxyLecturePack.getId();
            model.title = yxyLecturePack.getPackName();
            model.count = yxyLecturePack.getResources().size();
            model.schoolNick = yxyLecturePack.getSchoolNick();
            model.classNick = yxyLecturePack.getClassName();
            model.classId = yxyLecturePack.getClassId();
            model.userNick = yxyLecturePack.getUserNick();
            Long packSize = yxyLecturePack.getPackSize();

            if (null != packSize) {
                Double valueOf = Double.valueOf(packSize + "");
                Double file = valueOf / 1024;
                BigDecimal bg = new BigDecimal(file);
                double f1 = bg.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                model.packSize = f1;
            } else {
                model.packSize = 0.0;

            }
            model.dateFormat = DateToolUtils.format(yxyLecturePack.getPreDate(), DateToolUtils.FORMAT_SHORT_YMD);
            model.resources = resModels;

            listModel.add(model);
        }
        Page<RespModel> respPage = new PageImpl<>(listModel, pageable, total);
        return respPage;
    }

    protected static class ReqModel extends YxyApiPageReqModel {
        public String bookContent;
        public String classId;
        public String beginDate;
        public String endDate;
        public String keyword;

        @Override
        public void autoCheck() {
            Assert.notNull(StringUtils.defaultIfBlank(bookContent, null), "请选择目录");
        }
    }

    public class ResModel {
        public String formatId;
        public String title;
        public Integer orderNum;
        public Integer courseType;
        public Integer fileSize;
    }

    protected static class RespModel extends YxyApiRespModel {
        // 授课包ID
        public String id;
        public String title;
        public int count;
        // 贡献者学校名称
        public String schoolNick;
        // 班级id
        public String classId;
        // 贡献者名称
        public String userNick;
        // 创建时间（收录时间）
        public String dateFormat;
        // 发送给的班级
        public String classNick;
        // 资源
        public List<ResModel> resources;

        public Double packSize;
    }
}
